<?php
declare(strict_types=1);

namespace App\Repository\Admin;

use App\Model\User;

class UserRepository
{
    public function findAdminByName(string $name): ?User
    {
        return User::where('name', $name)
            ->where('role', 'admin')
            ->first();
    }

    public function getPaginatedUsers(array $filter, int $page = 1, int $perPage = 15)
    {
        return User::when(isset($filter['name']), fn ($query) => $query->where('name', $filter['name']))
            ->when(isset($filter['email']), fn ($query) => $query->where('email', $filter['email']))
            ->when(isset($filter['role']), fn ($query) => $query->where('role', $filter['role']))
            ->when(isset($filter['status']), fn ($query) => $query->where('status', $filter['status']))
            ->when(isset($filter['points']), function ($query) use ($filter) {
                $op = $filter['points_op'] ?? '=';
                $op = in_array($op, ['>', '<', '=', '>=', '<=']) ? $op : '=';
                return $query->where('points', $op, $filter['points']);
            })
            ->when(isset($filter['last_login_at']), function ($query) use ($filter) {
                $op = $filter['last_login_at_op'] ?? '=';
                $op = in_array($op, ['>', '<', '=', '>=', '<=']) ? $op : '=';
                return $query->where('last_login_at', $op, $filter['last_login_at']);
            })
            ->when(isset($filter['last_login_ip']), fn ($query) => $query->where('last_login_ip', $filter['last_login_ip']))
            ->when(isset($filter['created_at']), function ($query) use ($filter) {
                $op = $filter['created_at_op'] ?? '=';
                $op = in_array($op, ['>', '<', '=', '>=', '<=']) ? $op : '=';
                return $query->where('created_at', $op, $filter['created_at']);
            })
            ->when(isset($filter['email_verified_at']), function ($query) use ($filter) {
                $op = $filter['email_verified_at_op'] ?? '=';
                $op = in_array($op, ['>', '<', '=', '>=', '<=']) ? $op : '=';
                return $query->where('email_verified_at', $op, $filter['email_verified_at']);
            })
            ->paginate($perPage, page: $page);
    }

    public function getUser(int $id)
    {
        return User::find($id);
    }

    public function getUserDetail(int $id)
    {
        return User::with(['articles' => fn ($query) => $query->latest()->limit(10)])
            ->find($id);
    }

    public function updateByModel(User $user)
    {
        $user->save();
    }
}